package com.rongke.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.commons.JsonResp;
import com.rongke.model.PropValue;
import com.rongke.model.ShoppingCar;
import com.rongke.model.Sku;
import com.rongke.redis.CacheUtil;
import com.rongke.service.PropValueService;
import com.rongke.service.ShoppingCarService;
import com.rongke.service.SkuService;
import com.rongke.utils.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @ShoppingCarController
 * @购物车Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/shoppingCar")
@Transactional
@CrossOrigin
public class ShoppingCarController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private ShoppingCarService shoppingCarService;
    @Autowired
    private PropValueService propValueService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private CacheUtil cacheUtil;

    /**
     * @添加购物车
     * @param shoppingCar
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add1", method = RequestMethod.POST)
    public JsonResp addShoppingCar1(@RequestBody ShoppingCar shoppingCar,String propStr) {
        log.debug("添加购物车");
        if(StringUtil.isEmpty(propStr)){
            return JsonResp.fa("参数不能为空");
        }
        EntityWrapper<Sku> ew=new EntityWrapper<>();
        ew.eq("prop_str",propStr);
        Sku sku=skuService.selectOne(ew);
        if(sku==null){
            return  JsonResp.fa("参数错误");
        }
        EntityWrapper<ShoppingCar> ewCar=new EntityWrapper<>();
        ewCar.eq("sku_id",sku.getId());
        ShoppingCar sc=shoppingCarService.selectOne(ewCar);
        if(sc!=null){
            sc.setGoodsNum(sc.getGoodsNum()+shoppingCar.getGoodsNum());
            shoppingCarService.updateById(sc);
        }else {
            shoppingCar.setSkuId(sku.getId());
            shoppingCar.setGmtDatetime(new Date());
            shoppingCarService.insert(shoppingCar);
        }
        EntityWrapper<ShoppingCar> count=new EntityWrapper<>();
        count.eq("muser_id",shoppingCar.getMuserId());
        int n= shoppingCarService.selectCount(count);
        return JsonResp.ok(n);
    }
    /**
     * @添加购物车(添加到reids)
     * @param skuId
     * num 商品数量
     * token 令牌
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.GET)
    public JsonResp addShoppingCar(String skuId,Integer num,String token) {
        log.debug("添加购物车");
        JSONObject json = new JSONObject();
        json.put("skuId", skuId);
        json.put("num", num);
        String str[] = {json.toJSONString()};

        Set set = null;
        String str2[] = null;
        if (!cacheUtil.hasKey(token)) {
            return JsonResp.fa("未登录或登录超时，请重新登录");
        }
        Long userId = Long.valueOf(cacheUtil.get(token));
        if (cacheUtil.hasKey("shopCar" + userId)) {
            set = cacheUtil.getSet("shopCar" + userId);
            Object obj[] = set.toArray();
            int length = obj.length;
            int i = 0;
            for (; i < obj.length; i++) {
                JSONObject jsonCar = JSONObject.parseObject(String.valueOf(obj[i]));
                if (jsonCar.getString("skuId").equals(skuId)) {
                    Integer nums=Integer.valueOf(jsonCar.getString("num"));
                    jsonCar.put("num", num+nums);
                    obj[i] = jsonCar;
                    break;
                }
            }
            if (i == obj.length) {
                length++;
            }
            str2 = new String[length];
            for (int m = 0; m < obj.length; m++) {
                str2[m] = String.valueOf(obj[m]);
            }
            if (length == obj.length + 1) {
                str2[obj.length] = json.toJSONString();
            }

            cacheUtil.delkey("shopCar" + userId);
            cacheUtil.addSet("shopCar" + userId, str2);
        } else {
            cacheUtil.addSet("shopCar" + userId, str);
        }
        List<JSONObject> shoppingCars = new ArrayList<>();
        Set scSet = cacheUtil.getSet("shopCar" + userId);
        Iterator<String> its = scSet.iterator();
        while (its.hasNext()) {
            Object obj = its.next();
            JSONObject sc = JSONObject.parseObject(String.valueOf(obj));
            shoppingCars.add(sc);
        }
        return JsonResp.ok(shoppingCars);
    }


    /**
     * @修改购物车
     * @param shoppingCar
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateShoppingCar(@RequestBody ShoppingCar shoppingCar){
        log.debug("修改购物车");
        shoppingCar.setUptDatetime(new Date());
        shoppingCarService.updateById(shoppingCar);
        return JsonResp.ok(shoppingCar);
    }



    /**
     * @根据id查找购物车
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectShoppingCar(Long id){
        log.debug("查找购物车");
        ShoppingCar shoppingCar = shoppingCarService.selectById(id);
        return JsonResp.ok(shoppingCar);
    }



    /**
     * @根据条件查找购物车
     * @param shoppingCar
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/selectByCondition1", method = RequestMethod.POST)
    public JsonResp selectShoppingCarByCondition1(@RequestBody ShoppingCar shoppingCar){
        log.debug("根据条件查找购物车");
        if(shoppingCar==null)
            return JsonResp.toFail("参数不能为空");
        List<ShoppingCar> shoppingCarList=shoppingCarService.selectByCondition(shoppingCar);
//        Set<PropValue> pvs=new HashSet<>();
       Set<String> pvs=new HashSet<>();
        //获取购物车中所有属性对象
        for (ShoppingCar sc:shoppingCarList) {
            List<Sku> skuList=sc.getSkuList();
            for (Sku s:skuList ) {
                String propStr[]=s.getPropStr().split(",");
                for (String str:propStr) {
//                    PropValue pv=new PropValue();
//                    pv.setPropNameId(Long.valueOf(str.split("-")[0]));
//                    pv.setId(Long.valueOf(str.split("-")[1]));
//                    pvs.add(pv);
                    pvs.add(str.split("-")[1]);

                }
            }
        }
        //根据属性id获取属性值
        EntityWrapper<PropValue> ew=new EntityWrapper<>();
        ew.in("id",pvs);
        List<PropValue> pvList=propValueService.selectList(ew);
        //循环遍历
        for (ShoppingCar sc:shoppingCarList) {
            List<Sku> skuList=sc.getSkuList();
            for (Sku s:skuList ) {
                List<PropValue> pvalues=new ArrayList<>();
                String propStr[]=s.getPropStr().split(",");
                    for (String str:propStr) {
                        int i=0,y=pvList.size();
                        for(;i<y;i++){
                        String pvStr=str.split("-")[1];
                          if(pvStr.equals(String.valueOf(pvList.get(i).getId()))){
                              pvalues.add(pvList.get(i));
                              break;
                          }
                    }
                }
                s.setPropValues(pvalues);
            }
        }

        return JsonResp.ok(shoppingCarList);
    }


    /**
     * @根据条件查找购物车（从redis查询）
     * @return 返回值JsonResp
     */
        @RequestMapping(value = "/selectByCondition", method = RequestMethod.GET)
        public JsonResp selectShoppingCarByCondition(String token){
        log.debug("根据条件查找购物车（从redis查询）");
        if(!cacheUtil.hasKey(token)){
            return JsonResp.fa("未登录或登录超时，请重新登录");
        }
        Long userId=Long.valueOf(cacheUtil.get(token));
        if(!cacheUtil.hasKey("shopCar"+userId)){
            return JsonResp.fa("购物车尚未添加商品");
        }
        Set set=cacheUtil.getSet("shopCar"+userId);
        Set<String> skuIds=new HashSet<>();
        JSONObject jsonCar=null;
            Object obj[]= set.toArray();
            int i=0;
            for(;i<obj.length;i++){
                 jsonCar=JSONObject.parseObject(String.valueOf(obj[i]));
                skuIds.add(String.valueOf(jsonCar.get("skuId")));
            }

        List<Sku> skuList = skuService.selectSkuListAndIdIn(skuIds);
        for(i=0;i<obj.length;i++){
             jsonCar=JSONObject.parseObject(String.valueOf(obj[i]));
            for(int m=0,n=skuList.size();m<n;m++){
                Sku sku=skuList.get(m);
                if(jsonCar.getString("skuId").equals(String.valueOf(sku.getId()))){
                    sku.setNums(Integer.valueOf(jsonCar.getString("num")));
                    break;
                }
            }
        }
        return JsonResp.ok(skuList);
    }


    /**
     * @购物车改变商品数量
     * @param skuId  购物车id
     *   num   商品数
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/changeNums", method = RequestMethod.GET)
    public JsonResp changeNums(String skuId,Integer num,String token){
        log.debug("购物车改变商品数量");
        if(!cacheUtil.hasKey(token)){
            return JsonResp.fa("未登录或登录超时，请重新登录");
        }
        Long userId=Long.valueOf(cacheUtil.get(token));
        Set set=cacheUtil.getSet("shopCar"+userId);
        Object obj[]= set.toArray();
        String str[]=new String[set.size()];
        int i=0;
        for(;i<obj.length;i++){
            JSONObject jsonCar=JSONObject.parseObject(String.valueOf(obj[i]));
                if(jsonCar.getString("skuId").equals(skuId)){
                    jsonCar.put("num",num);
                    obj[i]=jsonCar;
                    break;
                }
        }
        for(int m=0;m<obj.length;m++){
            str[m]=String.valueOf(obj[m]);
        }
        cacheUtil.delkey("shopCar"+userId);
        cacheUtil.addSet("shopCar"+userId,str);
        return JsonResp.ok();
    }



    /**
     * @删除购物车某个商品
     * @param skuIds
     * token 令牌
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/delGoods", method = RequestMethod.GET)
    public JsonResp delGoods(String skuIds,String token) {
        log.debug("删除购物车某个商品");
        if (!cacheUtil.hasKey(token)) {
            return JsonResp.fa("未登录或登录超时，请重新登录");
        }
        String skuIdArr[] = skuIds.split(",");
        List<String> skuList = Arrays.asList(skuIdArr);
        Long userId = Long.valueOf(cacheUtil.get(token));
        Set set = cacheUtil.getSet("shopCar" + userId);
        Object obj[] = set.toArray();
        List<JSONObject> jsonList = new ArrayList<>();
        int i = 0;
        for (; i < obj.length; i++) {
            JSONObject jsonCar = JSONObject.parseObject(String.valueOf(obj[i]));
            int m = 0, n = skuList.size();
            for (; m < n; m++) {
                if (jsonCar.getString("skuId").equals(skuList.get(m))) {
                    break;
                }
            }
            if (m == n) {
                jsonList.add(jsonCar);
            }
        }
        if (!jsonList.isEmpty()) {
            String str[] = new String[jsonList.size()];
            for (int m = 0, n = jsonList.size(); m < n; m++) {
                JSONObject json = jsonList.get(m);
                str[m] = json.toJSONString();
            }
            cacheUtil.delkey("shopCar" + userId);
            cacheUtil.addSet("shopCar" + userId, str);
        }else{
            cacheUtil.delkey("shopCar" + userId);
        }

        return JsonResp.ok();
    }





}





